/**
 * $Revision: 1.1 $
 * $Date: 2011/10/24 09:21:57 $
 *
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.feng.demo.jakartacommons.mina.codec;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * Decoder class that parses ByteBuffers and generates XML stanzas. Generated
 * stanzas are then passed to the next filters.
 * 
 * @author Gaston Dombiak
 */
public class XMPPDecoder implements ProtocolDecoder {
	private Charset charset = Charset.forName("UTF-8");
	private static String CONTEXT = XMPPDecoder.class.getName()
	+ ".context";

	@Override
	public void dispose(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		XMLLightweightParser parser = (XMLLightweightParser) session.getAttribute("XML-PARSER");
		// Parse as many stanzas as possible from the received data
		parser.read(in);

		if (parser.areThereMsgs()) {
			for (String stanza : parser.getMsgs()) {
				out.write(stanza);
			}
		}
		Context ctx = getContext(session);
		decodeAuto(ctx, in, out);

	}

	private Context getContext(IoSession session) {
		Context ctx = (Context) session.getAttribute(CONTEXT);
		if (ctx == null) {
			ctx = new Context();
			session.setAttribute(CONTEXT, ctx);
		}
		return ctx;
	}

	private void decodeAuto(Context ctx, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException {
		boolean mark = false;
		while (in.hasRemaining()) {
			byte b = in.get();
			switch (b) {
			case '\r':
				break;
			case '\n':
				mark = true;
				break; // 跳出switch
			default:
				ctx.getBuf().put(b);
			}

			if (mark) {
				IoBuffer t_buf = ctx.getBuf();
				t_buf.flip();
				try {
					out.write(t_buf.getString(charset.newDecoder()));
				} finally {
					t_buf.clear();
				}
			}
		}
	}

	@Override
	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception {
		// TODO Auto-generated method stub

	}

	private class Context {
		private IoBuffer buf;

		public Context() {
			buf = IoBuffer.allocate(100).setAutoExpand(true);
		}

		public IoBuffer getBuf() {
			return buf;
		}
	}

}
